package com.example.a12.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;

import com.example.a12.bean.LoginInfo;

//import androidx.annotation.Nullable;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    //    创建数据库
    private static final String DB_NAME = "MySQLite.db";
    // 定义新建登录信息数据表语句
     private static final String create_users = "create table users(username varchar(32), password varchar(32))";
    public MySQLiteOpenHelper(@Nullable Context context) {
        super(context, DB_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(create_users);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    //   注册功能：往数据表中新增一条用户登录信息
    public long register(LoginInfo loginInfo) {
        SQLiteDatabase database1 = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", loginInfo.getUsername());
        cv.put("password", loginInfo.getPassword());
        long users = database1.insert("users", null, cv);
        return users;
    }
    //   登录功能：查询数据表中是否有符合的用户名密码
    public boolean login(String username, String password) {
        SQLiteDatabase database2 = getWritableDatabase();
        boolean results = false;
        Cursor users = database2.query("users",null,"username like ?", new String[]{username}, null,null,null);
        if (users != null) {
            while (users.moveToNext()) {
                String password1 = users.getString(1);
                results = password1.equals(password);
                return results;
            }
        }
        return false;
    } // 修改密码：更新数据库表中用户名密码
    public int update(String username,String password, String newPassword) {
        SQLiteDatabase database3 = getWritableDatabase();
        ContentValues cv3 = new ContentValues();
        boolean haveLogin = login(username, password);
        if (haveLogin) {
            cv3.put("username", username);
            cv3.put("password", newPassword);
        } else {
            int state = -1;
            return state;
        }
        int updateSuccess = database3.update("users", cv3, "username = ?", new
                String[]{username});
        return updateSuccess;
    }
}
